import "ol/ol.css";
import {
  mount,
  addPoint,
  addLine,
  addPolygon,
  addImage,
  drawGtaph,
  addArrowLine,
} from "./core/index";

function insertDom(cb) {
  const mainDom = document.getElementById("app");
  const toolbar = document.createElement("div");

  toolbar.style.position = "absolute";
  toolbar.style.top = "4px";
  toolbar.style.right = "8px";
  toolbar.style.zIndex = "1000";
  toolbar.style.backgroundColor = "rgba(255, 255, 255, 0.5)";
  toolbar.style.borderRadius = "5px";
  toolbar.style.padding = "5px";

  const btnData = [
    { label: "点", value: "Point" },
    { label: "线", value: "LineString" },
    { label: "矩形", value: "Rect" },
    { label: "圆", value: "Circle" },
    { label: "多边形", value: "Polygon" },
  ];
  const btn = document.createElement("button");
  btn.style.marginRight = "8px";
  /// 点击切换绘图类型
  let activeBtn = null;
  const clickHandler = (e) => {
    if (activeBtn) {
      activeBtn.classList.remove("active-btn");
    }
    activeBtn = e.target;
    activeBtn.classList.add("active-btn");
    const type = e.target.getAttribute("data-type");
    cb(type);
  };
  btnData.forEach((v) => {
    const shapeBtn = btn.cloneNode(true);
    shapeBtn.innerText = v.label;
    shapeBtn.setAttribute("data-type", v.value);
    shapeBtn.addEventListener("click", clickHandler, false);
    toolbar.appendChild(shapeBtn);
  });
  btn.remove(); //销毁
  mainDom.appendChild(toolbar);
}

function init() {
  const mainDom = document.getElementById("app");
  const map = mount(mainDom);

  addPoint(map);
  addLine(map);
  addPolygon(map);
  addImage(map);
  const startDraw = drawGtaph(map, (longlats) => {});
  insertDom(startDraw);

  // 绘制方向线
  addArrowLine(map);

  map.getView().animate({
    center: [108.95419846, 34.17228769],
    zoom: 1,
    duration: 1000,
  });
}

document.addEventListener("DOMContentLoaded", () => {
  console.log("vite is running!");
  init();
});
